﻿using OnHook.Business.Dto.Bjl;
using OnHook.Business.Dto.Xue;
using OnHook.Business.IServices;
using OnHook.Business.IServices.Common;
using OnHook.Business.Vo.Xue;
using OnHook.Common;
using OnHook.Common.Extension;
using OnHook.Domain.Entities;
using OnHook.Domain.Enums;
using OnHook.Framework.Exceptions;
using OnHook.Framework.Extensions;
using OnHook.Framework.Ioc;
using OnHook.Framework.Pager;
using OnHook.Common.UtilsHelper;
using EasyTool;
using Mapster;
using Microsoft.AspNetCore.Http.HttpResults;
using NPOI.Util;
using SqlSugar;

namespace OnHook.Business.Services
{
    /// <summary>
    /// 靴
    /// </summary>
    public class XueService(ISqlSugarClient db, IRedisCacheService redisCacheService, IJwtService jwtService) : IXueService, IScoped
    {
        private readonly ISqlSugarClient _db = db;
        private readonly IRedisCacheService _redisCacheService = redisCacheService;
        private readonly IJwtService _jwtService = jwtService;

        /// <summary>
        /// 同步结果
        /// </summary>
        /// <param name="createDto"></param>
        /// <returns></returns>
        public async Task SyncXueInfoAsync(BjlCreateDto createDto)
        {
            var recod = createDto.Adapt<Xue>();
            var userInfo = _jwtService.GetCurrentUser();

            #region 靴

            var item = await _db.Queryable<Xue>().FirstAsync(x => x.Code == recod.Code);
            if (item != null)
            {
                item.Copy(recod);
                item.Round = createDto.Details.Count;
                await _db.Updateable(item).ExecuteCommandAsync();
                //删除原来的明细
                await _db.Deleteable<XueDetail>().Where(x => x.XueId == item.Id).ExecuteCommandAsync();
            }
            else
            {
                item = recod;
                item.Period = await _redisCacheService.Increment();
                item.Id = IdHelper.NextId();
                item.CreateUserId = userInfo?.Id ?? 0;
                item.CreateUserName = userInfo?.UserName ?? "";
                item.Round = createDto.Details.Count;
                item.Status = EnumStatus.Enable;

                await _db.Insertable(item).ExecuteCommandAsync();
            }
            #endregion

            #region 明细

            var details = createDto.Details.Select((ele, index) =>
            {
                var e = ele.Adapt<XueDetail>();
                e.Round = index + 1;
                e.XueId = item.Id;
                e.Id = IdHelper.NextId();
                return e;
            }).ToList();

            await _db.Insertable(details).ExecuteCommandAsync();

            #endregion
        }
        #region 查询

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="searchDto"></param>
        /// <returns></returns>
        public async Task<PagedList<XueListVo>> GetXuePagedListAsync(XuePageSearchDto searchDto)
        {
            searchDto ??= new XuePageSearchDto();
            var query = _db.Queryable<Xue>().Where(x => x.Status == EnumStatus.Enable && !x.DelFlag)//.Includes(x=>x.Details)
                .WhereIF(searchDto.Keyword.IsNotEmpty(), x => x.Code.Contains(searchDto.Keyword))
                .WhereIF(searchDto.Period.HasValue, x => x.Period == searchDto.Period!.Value);
            ;
            var recordCount = new RefAsync<int>();
            var xueList = await query.ToPageListAsync(searchDto.PageIndex, searchDto.PageSize, recordCount);
            return searchDto.ToPagedList(xueList.Adapt<List<XueListVo>>(), recordCount);
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="searchDto"></param>
        /// <returns></returns>
        public async Task<List<XueListVo>> GetXueListAsync(XueSearchDto searchDto)
        {
            searchDto ??= new XuePageSearchDto();
            var query = _db.Queryable<Xue>().Where(x => x.Status == EnumStatus.Enable)//.Includes(x=>x.Details)
                .WhereIF(searchDto.Keyword.IsNotEmpty(), x => x.Code.Contains(searchDto.Keyword))
                .WhereIF(searchDto.Period.HasValue, x => x.Period == searchDto.Period!.Value);
            ;
            var xueList = await query.ToListAsync();
            return xueList.Adapt<List<XueListVo>>();
        }

        /// <summary>
        /// 查询明细
        /// </summary>
        /// <param name="xueId"></param>
        /// <returns></returns>
        public async Task<XueVo> GetXueDetail(long xueId)
        {
            var entity = await _db.Queryable<Xue>().Includes(x => x.Details).FirstAsync(x => x.Id == xueId && !x.DelFlag);
            return entity.Adapt<XueVo>();
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xueId"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task DeleteXueAsync(long xueId)
        {
            var entity = await _db.Queryable<Xue>().FirstAsync(x => x.Id == xueId);
            if (entity != null)
            {
                entity.DelFlag = true;
                await _db.Updateable(entity).ExecuteCommandAsync();
            }

        }
    }
}
